package com.javawork.igossip;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import com.javawork.igossip.model.*;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.provider.OpenableColumns;

public class LocalStorageHelper {

	static DBHelper helper;
	static SQLiteDatabase db;
	static Context context;

	public static void initLocalStorage(Context context) {
		helper = new DBHelper(context);
		db = helper.getWritableDatabase();
		LocalStorageHelper.context = context;
	}

	public static void finalizeLocalStorage() {
		helper.close();
	}

	public static Bitmap retrieveAvatar(String path) {
		String p = context.getFilesDir().getAbsolutePath();
		Bitmap b = BitmapFactory.decodeFile(p + File.pathSeparator + path);
		return b;
	}
	
	public static void saveAvatar(User user){
		String fname=user.uid.toString()+".png";
		try {
			FileOutputStream fout=context.openFileOutput(fname, context.MODE_PRIVATE);
			user.photo.compress(CompressFormat.PNG, 100, fout);
			fout.close();
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}

	public static boolean tryRetriveMyUserInfo(User userinfo) {
		if (db.isOpen() == false)
			db = helper.getWritableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM user", null);
		if (cur.moveToFirst()) {
			userinfo.username = cur.getString(0);
			userinfo.password = cur.getString(1);
			userinfo.gender = cur.getInt(2);
			userinfo.uid = cur.getInt(3);
			userinfo.description = cur.getString(4);
			userinfo.photo_path = cur.getString(5);
			userinfo.photo = null;
			String tags = cur.getString(6);
			userinfo.tags.clear();
			Collections.addAll(userinfo.tags, tags.split(" "));
			cur.close();
			return true;
		} else
			cur.close();
		return false;
	}

	public static void updateUserInfo(User userinfo) {
		db.delete("user", null, null);
		StringBuffer tags = new StringBuffer();
		for (String s : userinfo.tags) {
			tags.append(s);
			tags.append(' ');
		}
		db.execSQL("INSERT INTO user VALUES(?,?,?,?,?,?,?)",
				new Object[] { userinfo.username, userinfo.password,
						userinfo.gender, userinfo.uid, userinfo.description,
						userinfo.photo_path, tags.toString() });
	}

	public static ArrayList<Gossip> fetchAllNewsFeed() {
		ArrayList<Gossip> list = new ArrayList<Gossip>();
		if (db.isOpen() == false)
			db = helper.getWritableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM gossip", null);
		if (cur.moveToFirst()) {
			do {
				Gossip g = new Gossip();
				g.uid = cur.getInt(0);
				g.content = cur.getString(1);
				g.picture_path = cur.getString(2);
				g.reply_count = cur.getInt(3);
				g.target = cur.getString(4);
				g.source = cur.getString(5);
				g.datetime = new Date(cur.getString(6));
				list.add(g);
			} while (cur.moveToNext());
			cur.close();
		} else
			cur.close();
		return list;
	}

	// "(username NVARCHAR, gender INTEGER, userid INTEGER, description TEXT, photo VARCHAR, tags TEXT)");

	public static ArrayList<User> fetchAllContact() {
		ArrayList<User> list = new ArrayList<User>();
		if (db.isOpen() == false)
			db = helper.getWritableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM gossip", null);
		if (cur.moveToFirst()) {
			do {
				User userinfo = new User();
				userinfo.username = cur.getString(0);
				userinfo.gender = cur.getInt(1);
				userinfo.uid = cur.getInt(2);
				userinfo.description = cur.getString(3);
				userinfo.photo_path = cur.getString(4);
				list.add(userinfo);
			} while (cur.moveToNext());
			cur.close();
		} else
			cur.close();
		return list;
	}

	public static ArrayList<Message> fetchAllPrivateMessage() {
		ArrayList<Message> list = new ArrayList<Message>();
		if (db.isOpen() == false)
			db = helper.getWritableDatabase();
		Cursor cur = db.rawQuery("SELECT * FROM gossip", null);
		if (cur.moveToFirst()) {
			do {
				Message m = new Message();
				m.uid = cur.getInt(0);
				m.content = cur.getString(1);
				m.target = cur.getString(2);
				m.source = cur.getString(3);
				m.datetime = new Date(cur.getString(4));
				list.add(m);
			} while (cur.moveToNext());
			cur.close();
		} else
			cur.close();
		return list;
	}

	public static void saveNewGossips(ArrayList<Gossip> list) {
		for (Gossip g : list) {
			db.execSQL(
					"INSERT INTO gossip VALUES(?,?,?,?,?,?,?)",
					new Object[] { g.uid, g.content, g.picture_path,
							g.reply_count, g.target, g.source,
							g.datetime.toGMTString() });
		}
	}

	public static void saveNewMessages(ArrayList<Message> list) {
		for (Message m : list) {
			db.execSQL("INSERT INTO gossip VALUES(?,?,?,?)",
					new Object[] { m.uid, m.content, m.target, m.source,
							m.datetime.toGMTString() });
		}
	}

	public static void updateContacts(ArrayList<User> list) {
		for (User userinfo : list) {
			StringBuffer tags = new StringBuffer();
			for (String s : userinfo.tags) {
				tags.append(s);
				tags.append(' ');
			}
			db.execSQL("INSERT INTO user VALUES(?,?,?,?,?,?)", new Object[] {
					userinfo.username, userinfo.gender,
					userinfo.uid, userinfo.description, userinfo.photo_path,
					tags.toString() });
		}
	}

	// db.execSQL("CREATE TABLE IF NOT EXISTS user"
	// +
	// "(username NVARCHAR, password VARCHAR, gender INTEGER, userid INTEGER, description TEXT, photo VARCHAR, tags TEXT)");
	// db.execSQL("CREATE TABLE IF NOT EXISTS gossip"
	// +
	// "(id INTEGER, content TEXT, picture TEXT, replycount INTEGER, target NVARCHAR, source NVARCHAR, time TEXT)");
	// db.execSQL("CREATE TABLE IF NOT EXISTS message"
	// +
	// "(id INTEGER, content TEXT, target NVARCHAR, source NVARCHAR, time TEXT)");
	// db.execSQL("CREATE TABLE IF NOT EXISTS contact"
	// +

}
